import Outfit from '../models/Outfit.js';

// 获取搭配列表（支持分页和筛选）
export const getOutfits = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, season, occasion } = req.query;
    const userId = req.user._id;
    
    // 构建查询条件
    const query = { userId };
    
    if (season) {
      // 使用$in操作符查询季节数组中包含指定季节的搭配
      query.seasons = { $in: [season] };
    }
    
    if (occasion) {
      query.occasions = { $in: [occasion] };
    }
    
    // 分页计算
    const currentPage = parseInt(page);
    const size = parseInt(pageSize);
    const skip = (currentPage - 1) * size;
    
    // 查询数据
    const outfits = await Outfit.find(query)
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(size)
      .populate('clothesIds', 'name type color imageUrls');
    
    const total = await Outfit.countDocuments(query);
    
    res.json({
      items: outfits,
      total,
      page: currentPage,
      pageSize: size
    });
  } catch (error) {
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};

// 获取单个搭配详情
export const getOutfitDetail = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user._id;
    
    const outfit = await Outfit.findOne({ _id: id, userId })
      .populate('clothesIds', 'name type color imageUrls');
    
    if (!outfit) {
      return res.status(404).json({ message: '搭配不存在' });
    }
    
    res.json(outfit);
  } catch (error) {
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};

// 创建新搭配
export const createOutfit = async (req, res) => {
  try {
    const { 
      description, clothesIds, seasons, occasions, 
      outfitPhoto, finalOutfitImage, outfitInfo, canvasData 
    } = req.body;
    
    // 验证必填字段
    if (!finalOutfitImage || !canvasData) {
      return res.status(400).json({ message: '搭配图片和画布数据为必填项' });
    }
    
    const newOutfit = new Outfit({
      description,
      clothesIds: clothesIds || [],
      seasons: seasons || [],
      occasions: occasions || [],
      outfitPhoto,
      finalOutfitImage,
      outfitInfo: outfitInfo || [],
      canvasData,
      userId: req.user._id
    });
    
    await newOutfit.save();
    
    // 填充衣物信息
    const populatedOutfit = await Outfit.findById(newOutfit._id)
      .populate('clothesIds', 'name type color imageUrls');
    
    res.status(201).json(populatedOutfit);
  } catch (error) {
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};

// 更新搭配
export const updateOutfit = async (req, res) => {
  try {
    const { id } = req.params;
    const { 
      description, clothesIds, seasons, occasions, 
      outfitPhoto, finalOutfitImage, outfitInfo, canvasData 
    } = req.body;
    
    const userId = req.user._id;
    
    // 构建更新对象，只包含非undefined的字段
    const updateData = {
      updatedAt: Date.now()
    };
    
    if (description !== undefined) updateData.description = description;
    if (clothesIds !== undefined) updateData.clothesIds = clothesIds;
    if (seasons !== undefined) updateData.seasons = seasons;
    if (occasions !== undefined) updateData.occasions = occasions;
    if (outfitPhoto !== undefined) updateData.outfitPhoto = outfitPhoto;
    if (finalOutfitImage !== undefined) updateData.finalOutfitImage = finalOutfitImage;
    if (outfitInfo !== undefined) updateData.outfitInfo = outfitInfo;
    if (canvasData !== undefined) updateData.canvasData = canvasData;
    
    const updatedOutfit = await Outfit.findOneAndUpdate(
      { _id: id, userId },
      updateData,
      { new: true, runValidators: true }
    ).populate('clothesIds', 'name type color imageUrls');
    
    if (!updatedOutfit) {
      return res.status(404).json({ message: '搭配不存在' });
    }
    
    res.json(updatedOutfit);
  } catch (error) {
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};

// 获取推荐搭配
export const getRecommendedOutfits = async (req, res) => {
  try {
    const userId = req.user._id;
    const { limit = 5 } = req.query;
    
    // 简单的推荐逻辑：获取最近创建的搭配
    const recommendedOutfits = await Outfit.find({ userId })
      .sort({ createdAt: -1 })
      .limit(parseInt(limit))
      .populate('clothesIds', 'name type color imageUrls');
    
    res.json({
      items: recommendedOutfits,
      total: recommendedOutfits.length
    });
  } catch (error) {
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};

// 删除搭配
export const deleteOutfit = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user._id;
    
    const deletedOutfit = await Outfit.findOneAndDelete({ _id: id, userId });
    
    if (!deletedOutfit) {
      return res.status(404).json({ message: '搭配不存在' });
    }
    
    res.json({ message: '删除成功' });
  } catch (error) {
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};